from datetime import datetime

from app.extensions import db

class HouseInfo(db.Model):
    __tablename__ = 'houseinfo'
    # userid = db.Column(db.Integer, primary_key=True)
    houseid=db.Column(db.Integer, primary_key=True,autoincrement=True,comment='房源ID')
    title=db.Column(db.String(255), nullable=False,comment='房源标题')
    property_type=db.Column(
        db.Enum('公寓','别墅','商铺','房间',name='property_type_enum'),
        nullable=False,
        comment='物业类型'
    )
    rental_type=db.Column(
        db.Enum('整租','合租',name='rental_type_enum'),
        nullable=False,
        comment='租赁类型'
    )

    area=db.Column(db.Integer,nullable=False,comment='面积（平方米）')
    price=db.Column(db.Integer,nullable=False,comment='价格（元/月）')
    deposit=db.Column(db.Integer,default=0,comment='押金（元）')
    bedroom_count=db.Column(db.Integer,default=0,comment='卧室数量')
    livingroom_count=db.Column(db.Integer,default=0,comment='客厅数量')
    bathroom_count=db.Column(db.Integer,default=0,comment='卫生间数量')
    status=db.Column(
        db.Enum('pending','published','rented','maintenance','offline',name='status_enum'),
        default='pending',
        nullable=False,
        comment='状态：pending--待审核,published--已发布，rented--已出租，maintenance--维护中，offline--已下架'
    )
    publish_time=db.Column(
        db.TIMESTAMP,
        default=datetime.utcnow,
        comment='发布时间'
    )
    userid=db.Column(
        db.Integer,
        db.ForeignKey('users.userid'),
        nullable=False,
        comment='用户ID（房东）'
    )

    # 外键
    user=db.relationship(
        'User',backref='houses'
    )

    #创建索引
    __table_args__ = (
        db.Index('idx_userid','userid'),
        db.Index('idx_status','status'),
    )

    def __repr__(self):
        return f'<HouseInfo {self.houseid}>:{self.title}'

    #将模型转换为字典格式，便于json序列化
    def to_dict(self):
        return {
            'houseid': self.houseid,
            'title': self.title,
            'property_type': self.property_type,
            'rental_type': self.rental_type,
            'area': self.area,
            'price': self.price,
            'deposit': self.deposit,
            'bedroom_count': self.bedroom_count,
            'livingroom_count': self.livingroom_count,
            'bathroom_count': self.bathroom_count,
            'status': self.status,
            'publish_time': self.publish_time.isoformat() if self.publish_time else None,
            'userid': self.userid,
        }

    @classmethod
    def updatable_fields(cls):
        return [
            'title', 'property_type', 'rental_type', 'area', 'price',
            'deposit', 'bedroom_count', 'livingroom_count', 'bathroom_count',
            'status'
        ]

# # 添加新记录
# new_house = HouseInfo(
#     title='阳光公寓',
#     property_type='公寓',
#     rental_type='整租',
#     area=80,
#     price=3500,
#     userid=1
# )